#!/usr/bin/python
#coding: utf-8

################################
# file: httpHelp.py            #
# function:                    #
# author: xsseroot@gmail.com   #
# time: 2014-9-2 14:03         #
# update: 2014-9-4 16:34:11    #
################################

import httplib
import urllib
import time
from log import loger

####################
# httpHelper class
####################
class httpHelper():
	__contentType = ""
	__accept = ""
	__userAgent = ""
	__currentTry = 0
	__log = None
	__NumDic={1:"first",2:"seconds",3:"third",4:"fourth",5:"fifth",6:"sixth",7:"seventh",8:"eighth",9:"Ninth"}
	delay = 1
	maxTry = 3
	
	# initialization parameters mm_crawler
	def __init__(self,
				log=None,
				conType = "application/x-www-form-urlencodeed",
				accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*",
				userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 SE 2.X MetaSr 1.0"
				):
		self.__contentType = conType
		self.__accept = accept
		self.__userAgent = userAgent
		if log:
			self.__log = log
		else:		
			self.__log = loger()

	# Get request 
	def GetHtml(self,host,path,decode=None,port=80,timeout=5):
		conn = None
		reuslt = ""	
		for i in range(1,self.maxTry+1):
			if i != 1:
				self.__log.Info("Try the %s connection..." %  self.__NumDic[i])
			try:
				header = {"Content-type":self.__contentType,"Accept":self.__accept,"UserAgent":self.__userAgent}
				conn = httplib.HTTPConnection(host,port,True,timeout)
				conn.request('GET',path,"",header);
				response = conn.getresponse()
				self.__log.Debug("Status code:%s, http://%s%s" % (str(response.status),host,path))
				if response.status == 200 :
						if decode:
							reuslt = response.read().decode(decode)	
						else:
							reuslt = response.read()								
				break
			except Exception as e:
				self.__log.Error( "%s, request host:%s, port:%s fail. url:http://%s%s" % (str(e),host,port,host,path))
			finally:			   
				conn.close(); 
			if self.delay > 0 and self.maxTry != i:
				#print "delay"
				time.sleep(self.delay)
		return reuslt
